package uk.ac.aber.Blockmation;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;


/**
 * Reads Scotty type text files and get them as ArrayList of BufferedImages.
 *
 * @author Aron
 *
 */
public class ScottyIntoImages {
	
    /** keeps converted frame */
    private BufferedImage output = null;

    /** ArrayList for holding the whole Scotty file */
    private ArrayList<String> fileInArray = new ArrayList<String>();

    /** Class translating letters into colors */
    private OurColors ourColors = new OurColors();

    /**
     * Decodes the Scotty text file that contains animation's information
     * into ArrayList of BufferedImages.
     * @param fileName of the text file to decode.
     * @return ArrayList<BufferedImage> of converted frames. Null if there's been
     * a problem with reading the file in any way, whether it's corrupted or file
     * doesn't exist, etc.
     */
    public ArrayList<BufferedImage> decodeAsBufferedImages(String fileName) 
    {
    	try {
			readFileToArray(fileName);
		} catch (FileNotFoundException e1) {
			System.err.println("Cannot find file specified.");
			return null;
		}
        
        
		int noOfFrames;
		int frameSize;
		ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
		
		try {
			noOfFrames = Integer.parseInt( fileInArray.get(0) ); //first line should contain this, pos 0
			frameSize = Integer.parseInt( fileInArray.get(1) ); //second line
			
			String line;
			char colorLetter;
			
			BufferedImage img;
			int position = 2; //reading frames off from here
			
			// loops through lines making up frames
			for(int h=0; h< noOfFrames; h++)
			{
				// prepare the image with size of the frame size
				img = new BufferedImage(frameSize, frameSize, BufferedImage.TYPE_INT_RGB);

				
				if ( position == 2 || ( (position-2)%frameSize ) == 0)
				{
				// loops through file lines that makes up THIS particular frame
				for (int i=0; i < frameSize; i++)
				{
					// gets line by line
					line = fileInArray.get(position+i);
					
					// processes each line and converts letters to colors
					for (int j=0; j<line.length(); j++)
					{
						colorLetter = line.charAt(j);
						// sets pixels with RGB int value and getRGB() gives int.
						img.setRGB(j, i, ourColors.get(colorLetter).getRGB());
					}				
				}
				/*
				 * keeps track of the line in the file which each frame begins from 
				 */
				position+=frameSize;
				
				}
			
			images.add(img); // ready image added here
			}
		} catch(NumberFormatException e)
		{
			System.err.println("Seems like the file's corrupted. Wrong noOfFrames or frameSize.");
			return null;
		}
		
		System.out.println("Converted Scotty file to BufferedImages. NoOfFrame: " + images.size());
    	return images;
    	
    }
	
	/**
     * Reads the content of the file into ArrayList 'images' line by
     * line.
     *
     * @throws FileNotFoundException if file doesn't exist
     */
    private void readFileToArray(String fileName) throws FileNotFoundException
    {
        File f = new File(fileName);
        Scanner scanner = new Scanner(f);
        
        fileInArray.clear(); // emptying ArrayList just in case

        try
        {
            scanner = new Scanner(f);

            while (scanner.hasNext())
            {
                fileInArray.add(scanner.nextLine()); // adds lines from file
            }

            scanner.close(); // closes the streams
        }
        catch (NullPointerException e)
        {
            /* it means 'null' has been passed to Scanner constructor
             * so it's similar to the below exception and need to be handled
             * similarly outside this method.
             */
        	throw new FileNotFoundException();
        }
    }

}
